<template>
  <el-form>
    <el-form-item label="选择题目">
      <el-select v-model="selectedTopicId" placeholder="请选择题目" @change="onChange" :loading="loading">
        <el-option
          v-for="topic in topics"
          :key="topic.id"
          :label="`${topic.name}（${topic.desc}）`"
          :value="topic.id"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import axios from 'axios'

const props = defineProps({
  contestId: { type: String, required: true }
})
const emit = defineEmits(['change'])

const topics = ref([])
const loading = ref(false)
const selectedTopicId = ref('')

const fetchTopics = async () => {
  if (!props.contestId) return
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get('/api/students/topics', {
      params: { contestId: props.contestId },
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (res.data.code === 200) {
      topics.value = res.data.data
    } else {
      topics.value = []
    }
  } catch (e) {
    topics.value = []
  } finally {
    loading.value = false
  }
}

watch(() => props.contestId, fetchTopics, { immediate: true })

const onChange = (val) => {
  emit('change', topics.value.find(t => t.id === val))
}
</script>
